const app = getApp();
import { setUserInfo, getUserInfo } from '../../utils/store';
import api from "../../utils/apiInstance"
Page({  
  data: {  
    baseUrl: app.globalData.baseUrl,
    fileUrl: app.globalData.fileUrl,
    searchParam:{},
    cardList: [],
    isOutLink:false,
    id:'',
    isShowSignList:false,
    isShowPhone:false,
    signParams:{},
    currentDepart:"",
    currentDepartName:"",
    bigSearchShow:false,
    dePartList:[],
    bigSearchHeight:app.globalData.windowHeight + app.globalData.StatusBar,
    currentCardInde:0,
    isSanJiPx:false, //是否三级培训
    sanJiPx:['MonthlyTrainingPlan','WorkshopTraining','TeamTraining'],
    form:{},
    currentItem:{}
  },


  onLoad:function(params){
      const initTime = this.selectComponent("#searchTab").data.currentTime
      console.log('params',params,this.data.sanJiPx.includes(params.type));
      
      //扫码进入的情况
      if(params.id){
        this.setData({
          id:params.id,
          isOutLink:true,
         
        })
      }
      else{
        this.setData({
          searchParam: {
            endTime:initTime[1],
            startTime:initTime[0],
            projectType:params.type,
          },
          isSanJiPx:this.data.sanJiPx.includes(params.type)
         })
      }
     this.loadData();
  },
  async loadData(){
    var that=this;
    let res = "";
    if(this.data.isOutLink){
      res = await api.get(`/v1/openApi/staff/course/${that.data.id}?type=1`);
    }
    else{
      res = await api.post(`/v1/openApi/trainer/myCourse`,{ ...that.data.searchParam});
    }
    const data=res.rows||[res.data];

    data.length>0&&data.forEach(item=>{
      let tempArray = [];
      item.isShowSignList = false;
      if(item.staffSign&&item.staffSign.images.length>0){
        item.staffSign.images.forEach(inneritem => {
          tempArray.push({url:inneritem, closeable:false})
        });

        item.staffSign.images = tempArray
      }
    })
      that.setData({
        cardList: data
      })

    
  },

  //查询签到列表
  async doSearchForSignList(){
    const signRes = await api.post(`/v1/openApi/sign/manager/list`,{ ...this.data.signParams});
    const tempCard = JSON.parse(JSON.stringify(this.data.cardList))
    signRes.data.signRate = ((signRes.data.signedIn||0)+(signRes.data.notSignedIn||0))>0?(signRes.data.signedIn/(signRes.data.signedIn+signRes.data.notSignedIn)*100).toFixed(2):0

    tempCard[this.data.currentCardIndex].signListData = signRes.data

    this.setData({
      cardList:tempCard
     
    })
  },


  async doShowSignList(e){
    const tempCardList = this.data.cardList;
  
      let dePartRes = await api.get(`/v1/openApi/employee/search/departList`,{ trainId:e.target.dataset.item.id});
      dePartRes.data.unshift({deptName:"全部"})

      tempCardList[e.target.dataset.index].currentDepartName=dePartRes.data.length>0?dePartRes.data[0].deptName:''
      this.setData({
        currentDepart:dePartRes.data.length>0?dePartRes.data[0].id:'',
        dePartList:dePartRes.data||[]
      })


      this.setData({
        ["signParams.trainId"]: e.target.dataset.item.id,
        ["signParams.departId"]:this.data.currentDepart
      })
      
  
   
    
    tempCardList[e.target.dataset.index].isShowSignList = !tempCardList[e.target.dataset.index].isShowSignList;

    this.setData({
      currentCardIndex:e.target.dataset.index,
      cardList:tempCardList,
    })
    this.doSearchForSignList()
  },

  doAdd(e){
    wx.setStorageSync('lessionInfo', e.target.dataset.index);
    wx.navigateTo({
      url: `/pages/my-course-add/my-course-add?projectType=${this.data.searchParam.projectType}`,
    })
  },


  startSign(){
    wx.navigateTo({
      url: `/pages/comWebView/comWebView?url=${encodeURIComponent(app.globalData.signUrl)}`
    });
  },

  phoneChange(e){
    this.setData({
      ['form.phone']: e.detail.value
    })
  },

  async doPhoneSubmit(){
    if (!this.data.form.phone) {
      wx.showToast({
        title: '请输入手机号码！',
        icon: 'none',
        duration: 3000
      });
      return
    }
    const res = await api.post("/staffInfo/wx/updatePhone",{phone:this.data.form.phone})
    this.setData({
      isShowPhone:false
    })
    this.startCourse(this.data.currentItem);
  },


  searchSelect(e){

    const tempCard = JSON.parse(JSON.stringify(this.data.cardList))
    tempCard[this.data.currentCardIndex].currentDepartName = e.detail.deptName
    this.setData({
      ["signParams.departId"]:e.detail.id,
      cardList:tempCard
    })
    this.doSearchForSignList();

  },

  bindDateChange:function(e){
    this.setData({  
      currentTime: e.detail.value  
    })  
    this.loadData();
  },
  formatDate:function(date){
      const year = date.getFullYear();  
      const month = String(date.getMonth() + 1).padStart(2, '0'); // 月份从0开始，所以要加1  
      const day = String(date.getDate()).padStart(2, '0');  
      return `${year}-${month}-${day}`;  
  },

  //搜索返回
  doSearch(res){
    let newParams = {
      endTime:res.detail.currentTime[1],
      startTime:res.detail.currentTime[0],
      sign:Boolean(+res.detail.signStatus)
    }
    //全部要删去参数
    if(res.detail.signStatus=="2"){
      delete newParams.sign
    }
    this.setData({
      searchParam: Object.assign({},this.data.searchParam,newParams)
    })

    this.loadData();
  },

  signIn:function(item){

    let that=this;
    wx.showLoading({  
      title: '签到中', // 提示的内容  
      mask: true, // 是否显示透明蒙层，防止触摸穿透  
    });
    wx.request({
      url: that.data.baseUrl+'/v1/openApi/sign', //'+item.id,
      method: 'POST',
      data:{
         sapId:wx.getStorageSync('userinfo').siocSapNo,
         staffId:wx.getStorageSync('userinfo').staffId,
         type:1,
         trainId:item.id,
         images:item.imageList,
         courseId:item.id
      },
      header: {
        'Content-Type': 'application/json' // 请求头  
      },
      success(res) {
        wx.hideLoading();
        if(res.data.code==200){
          wx.showToast({  
            title: '签到成功！',  
            icon: 'success',  
            duration: 3000  
          });  
          that.loadData();
        }else{
          wx.showToast({  
            title: '签到失败,'+res.data.msg,  
            icon: 'none',  
            duration: 3000  
          });  
        }
      
      },fail(res){
          wx.hideLoading();
          wx.showToast({  
            title: '签到失败，请联系管理人员！',  
            icon: 'none',  
            duration: 3000  
          });  
      }
    });
  },

  checkPhone(){
    return new Promise(async (reslove,reject)=>{
      const res = await api.get(`/staffInfo/wx/getPhone`);
      console.log('res',res);
      if(res?.data?.phone){
        reslove(res.data.phone)
      }
      else{
        reslove('')
      }
    })
  },


  startCourse:async function(event){
    this.setData({currentItem:event})
    //检测是否有手机号
    const getPhone = await this.checkPhone();
    if(getPhone){
      let item= event.currentTarget.dataset.item; 
      const imageList = this.selectComponent(`#imageUp${event.currentTarget.dataset.index}`).data.imageList

      const tempArray = [];
      imageList.forEach(item=>{
        tempArray.push(item.url);
      })

      item.imageList = tempArray
      if(!item.imageList|| item.imageList.length==0){
        wx.showToast({  
          title: '请先上传签到图片',  
          icon: 'none',  
          duration: 3000  
        });  
        return;
      }
      this.signIn(item);
    }
    else{
      this.setData({
        isShowPhone:true
      })
    }
  },
   uploadCourse: function(event){
    let that = this;
    var index= event.currentTarget.dataset.index; 
    wx.chooseMedia({  
      count: 9, // 默认9  
      mediaType: ['image'],  
      sourceType: ['camera'],  
      camera: 'back', // 使用后置摄像头  
      success: function (res) {  
        var path= res.tempFiles[0].tempFilePath;
        wx.showLoading({  
          title: '签到图片上传中', // 提示的内容  
          mask: true, // 是否显示透明蒙层，防止触摸穿透  
        });
         wx.uploadFile({
          url:that.data.fileUrl+'/common/picUpload', 
          filePath: path,  
          name: 'file',
          success (res){
            let fileInfo= JSON.parse(res.data);
            let fileName=fileInfo.fileName;
            var list=that.data.cardList;
            if(!list[index].imageList){
              list[index].images=[];
              list[index].imageList=[];
            }
            list[index].images.push(fileName);
            list[index].imageList.push(path);
            that.setData({  
              cardList:list
            });  
            wx.hideLoading();
          },
          fail (err){
            wx.hideLoading();
            wx.showToast({  
              title: "上传失败",  
              icon: 'none', 
              duration: 3000
            }); 
          }
        });
      },
      fail:function(res){
        wx.showToast({  
          title: "操作失败",  
          icon: 'none', 
          duration: 3000
        }); 
      }
    });
  },
  doShowBigSearch(){
    this.setData({  
      bigSearchShow:true
    });  
  }
})
